﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ScopaSL.Gameplay;
using ScopaSL.State;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace ScopaSL.Rendering
{
    public partial class BoardRenderer : UserControl
    {
        private BoardState gameState;
        private List<CardRenderer> cardRenderers;
        private CardRenderer draggedCard;
        Image deck;
        DispatcherTimer timer;
        Point mousePosition;

        public BoardRenderer()
        {
            InitializeComponent();

            gameState = ScopaStateManager.GetState();
            cardRenderers = new List<CardRenderer>();

            deck = new Image();
            Uri uri = new Uri("/ScopaSL;component/Content/Images/Decks/Deck_Siciliane.png", UriKind.RelativeOrAbsolute);
            ImageSource img = new System.Windows.Media.Imaging.BitmapImage(uri);
            deck.SetValue(Image.SourceProperty, img);

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(33);
            timer.Tick += new EventHandler(Update);
            timer.Start();

            UpdateTableCards();

            this.MouseMove += new MouseEventHandler(Game_MouseMove);
            this.MouseLeftButtonUp += new MouseButtonEventHandler(Game_MouseLeftButtonUp);
        }

        void Update(object sender, EventArgs e)
        {
            Point mousePointer = this.mousePosition;// e.GetPosition(this);

            // Aggiornamento posizione carta trascinata
            if (draggedCard != null)
                draggedCard.UpdatePosition(mousePointer, new Size(LayoutRoot.Width, LayoutRoot.Height));            
        }


        public void AddCard(Card cInfo)
        {


            //Create a bitmap of the cropped size
            WriteableBitmap wb = new WriteableBitmap(90, 154);

            //Create a transform to move the Image to the top left
            CompositeTransform t = new CompositeTransform();
            t.TranslateX = -((cInfo.Value - 1) * LayoutRoot.Width);
            t.TranslateY = -(((int)cInfo.Color - 1) * LayoutRoot.Height);
            t.ScaleX = 0.84;
            t.ScaleY = 0.845;

            //Draw to the Writeable Bitmap
            wb.Render(deck, t);
            wb.Invalidate();



            CardRenderer cr = new CardRenderer();
            cr.SetCard(wb, cInfo.Value, (int)cInfo.Color);
            Canvas.SetLeft(cr, cInfo.CoordPosition.X);
            Canvas.SetTop(cr, cInfo.CoordPosition.Y);
            cardRenderers.Add(cr);
            LayoutRoot.Children.Add(cr);

            // Imposta un evento per memorizzare la carta quando si inizia il trascinamento
            cr.MouseLeftButtonDown += new MouseButtonEventHandler(card_MouseLeftButtonDown);
        }

        public void RemoveCard(Card cInfo)
        {
            int cardIndex = gameState.BoardBlocks.ElementAt(0).Cards.IndexOf(cInfo);

            CardRenderer cr = cardRenderers.ElementAt(cardIndex);
            cardRenderers.RemoveAt(cardIndex);
            LayoutRoot.Children.Remove(cr);

            cr.MouseLeftButtonDown -= card_MouseLeftButtonDown;
        }

        public void UpdateTableCards()
        {
            // Update cards on the table
            cardRenderers.Clear();
            var tableCardsInfo = gameState.BoardBlocks.ElementAt(0).Cards;

            //for (int i = 0; i < tableCardsInfo.Count; ++i)
            //    AddCard(tableCardsInfo[i]);
            for (int i = 0; i < 100; i++)
            {
                AddCard(tableCardsInfo[0]);
            }
            

            ResetZIndex();
        }

        public void ResetZIndex()
        {
            for (int i = 0; i < cardRenderers.Count; i++)
                Canvas.SetZIndex(cardRenderers[i], i);
        }

        void card_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Memorizza la carta trascinata
            draggedCard = (CardRenderer)sender;
            Canvas.SetZIndex(draggedCard, cardRenderers.Count);
        }


        void Game_MouseMove(object sender, MouseEventArgs e)
        {
            mousePosition = e.GetPosition(this);
            //Point mousePointer = e.GetPosition(this);

            //// Aggiornamento posizione carta trascinata
            //if (draggedCard != null)
            //    draggedCard.UpdatePosition(mousePointer, new Size(LayoutRoot.Width, LayoutRoot.Height));
        }

        void Game_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            // Rilascia le carte trascinate, se ce ne sono
            if (draggedCard == null) return;

            draggedCard.IsBeingDragged = false;
            draggedCard.WasTouched = false;
            draggedCard = null;

            ResetZIndex();
        }

    }
}
